<template>
  <div class="demo-upload-list" v-for="(item,index) in uploadList">
      <Image :src="item.url" fit="cover" width="100%" height="100%" />
      <div class="demo-upload-list-cover">
        <Icon type="ios-eye-outline" @click="handleView(item)"></Icon>
        <Icon type="ios-trash-outline" @click="handleRemove(item,index)"></Icon>
      </div>
  </div>
  <Upload
      :show-upload-list="false"
      :before-upload="handleBeforeUpload"
      :max-size="2048"
      multiple
      type="drag"
      style="display: inline-block;width:58px;">
    <div style="width: 58px;height:58px;line-height: 58px;">
      <Icon type="ios-camera" size="20"></Icon>
    </div>
  </Upload>
  <ImagePreview class="test-img" v-model="visible" :preview-list="[previewImg]" />

  <Input v-model="imgData" type="textarea" :rows="4" placeholder="此处显示base64数据" />
</template>

<script setup>
import {ref} from 'vue'
import { Base64 } from 'js-base64';

const visible=ref(false)
const uploadList=ref([])
const imgData=ref('')

const previewImg=ref('')
function handleView (imgItem) {
  previewImg.value=imgItem.url
  visible.value = true;
}

function getInfoByFile(file){
  // 获取图片信息

  const promise=new Promise((resolve,reject)=>{
    console.log(Base64.btoa(file))
    const reader=new FileReader()
    reader.readAsDataURL(file)
    reader.onload = (e) => {
      resolve({
        imgData:e.target.result
      })
    };
    reader.onerror = (error) => {
      console.error('图片读取失败:', error);
      reject('图片读取失败:', error)
    };
  })
  return promise
}

async function handleBeforeUpload(file){
  // 获取图片信息
  const info=await getInfoByFile(file)
  const{imgData:getData}=info
  imgData.value=getData
  uploadList.value=[{
    name:file.name,
    url:imgData
  }]
  return false

}
function handleRemove (file,index) {
  uploadList.value.splice(index,1)
  imgData.value=''
}
</script>

<style scoped>
.demo-upload-list{
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0,0,0,.2);
  margin-right: 4px;
}
.demo-upload-list img{
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover{
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0,0,0,.6);
}
.demo-upload-list:hover .demo-upload-list-cover{
  display: block;
}
.demo-upload-list-cover i{
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.ivu-tabs-tabpane :deep(.ivu-image-preview-wrap){
  position: absolute;
}
</style>

